const router = require('koa-router')()
const utlis = require('../utlis/common')
const { Role } = require('../models/roleSchema')
router.prefix('/roles')

//查询所有角色列表
router.get('/allList', async ctx => {
    try {
        const list = await Role.find({}, "_id roleName")
        ctx.body = utlis.success(list)
    } catch (error) {
        ctx.body = utlis.fail(`查询失败:${error.stack}`)
    }
})

//按页查询 角色列表
router.get('/list', async ctx => {
    const { roleName } = ctx.request.query
    const { page, skipIndex } = utlis.pager(ctx.request.query)
    try {
        let params = {}
        if (roleName) params.roleName = roleName;
        const query = Role.find(params)
        const total = await query.skip(skipIndex).limit(page.pageSize)
        const list = await Role.countDocuments(params)
        ctx.body = utlis.success({
            list,
            page: {
                ...page,
                total
            }
        })
    } catch (error) {
        ctx.body = utlis.fail(`查询失败:${error.stack}`)
    }
})

//角色操作： 创建 编辑和删除
router.post('/operate', async ctx => {
    const { _id, roleName, remark, action } = ctx.request.body
    let res, info
    try {
        if (action == 'create') {
            res = await Role.create({ roleName, remark })
            info = '创建时间'
        } else if (action = 'edit') {
            if (_id) {
                let params = { roleName, remark }
                params.update = new Date()
                res = await Role.findByIdAndUpdate(_id, params)
                info = '编辑成功'
            } else {
                ctx.body = utlis.fail('缺少参数params:_id')
                return
            }
        } else {
            if (_id) {
                res = await Role.findByIdAndDelete(_id)
                info = '删除成功'
            } else {
                ctx.body = utlis.fail('缺少参数params:_id')
            }
        }

        ctx.body = utlis.success(res, info)
    } catch (error) {

    }

})


module.exports = router